/*
 * This servlet adds/edits/deletes a lesson
 * it also creates/edits/deletes a live lesson
 */
package controllers.managecontrollers;

import classes.Breadcrumbs;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Course;
import models.Lesson;
import models.LiveLesson;
import dao.CourseDao;
import classes.HibernateUtil;
import dao.FileDao;
import dao.LessonDao;
import dao.LiveLessonDao;
import java.util.Set;
import models.Files;

/**
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class ManageLessonController extends HttpServlet {

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    /*
     * This method prepares the add edit lesson page
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("id") != null) {
            editLesson(Long.parseLong(request.getParameter("id")), request, response);
        } else {

            if (request.getParameter("idremove") != null) {
                removeLesson(Long.parseLong(request.getParameter("idremove")), request, response);
            }

            long courseid = 0; //standard vlaule

            //prepare dao
            HibernateUtil hu = new HibernateUtil();
            CourseDao cd = new CourseDao(hu.openSession());
            List<Course> courselist = cd.findAll();

            //set attributes
            request.setAttribute("allcourses", courselist); //set the courselist
            request.setAttribute("courseid", courseid); //set the courseid

            if (request.getParameter("idremove") == null) { //if it's not a remove, delete the lesson
                // Breadcrumbs
                Breadcrumbs[] breadcrumbs = {
                    new Breadcrumbs("Index", "Home"),
                    new Breadcrumbs("CourseLessonEdit", "Manage lessons"),
                    new Breadcrumbs("ManageLesson?courseid", "Add lesson")
                };
                request.setAttribute("breadcrumbs", breadcrumbs);

                //redirect the user
                RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_lessons.jsp");
                dispatcher.forward(request, response);
            }
        }
    }

    /**
     * this method adds/edits/removes a lesson depending on the request
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        long id = System.nanoTime();
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        boolean freeLesson = false; //set these variables as false
        boolean liveLesson = false;

        long courseid;

        if (request.getParameter("isfree") != null) { //check if lesson is free
            freeLesson = true;
        }

        if (request.getParameter("islive") != null) { //check is lesson is a live lesson
            liveLesson = true;
        }


        if (request.getParameter("courseid") == null) {
            courseid = Long.parseLong(request.getParameter("course"));
        } else {
            courseid = Long.parseLong(request.getParameter("courseid"));
        }

        CourseDao cdao = new CourseDao(hu.openSession());
        Course course = cdao.get(courseid);

        if (request.getParameter("formoption").equals("Lessonadd")) { //Add a new lesson

            //-----------------------------------------------------
            //Input controle
            //-----------------------------------------------------
            if (name == null || name.trim().equals("")) {
                sendForward(request, response, courseid, false);
                return;
            }

            LessonDao ld = new LessonDao(hu.openSession());
            Lesson lec = new Lesson(id, name, description, course, freeLesson, liveLesson);


            if (liveLesson) { //if it is also a liveLesson, create the object

                //---------------------------------------
                //input controle first
                //---------------------------------------
                if (request.getParameter("hour").equals("-") || request.getParameter("minute").equals("-") || request.getParameter("day").equals("-") || request.getParameter("month").equals("-") || request.getParameter("year").equals("-") || request.getParameter("embedStream").trim().equals("") || request.getParameter("embedStream") == null) {
                    sendForward(request, response, courseid, false);
                    return;
                }
                ld.save(lec); //save the lecture

                //Get the date from the form
                int hour = Integer.parseInt(request.getParameter("hour"));
                int minute = Integer.parseInt(request.getParameter("minute"));
                int day = Integer.parseInt(request.getParameter("day"));
                int month = Integer.parseInt(request.getParameter("month"));
                int year = Integer.parseInt(request.getParameter("year"));

                long livelessonid = System.nanoTime();
                String embedStream = request.getParameter("embedStream");
                Lesson lastLesson = ld.getLast();

                LiveLesson ll = new LiveLesson(livelessonid, lastLesson, "not started", embedStream); //set live lesson as not started yet
                ll.setDate(year, month, day, hour, minute);
                LiveLessonDao lld = new LiveLessonDao(hu.openSession());
                lld.save(ll); //save the live lecture
            } else {
                ld.save(lec); //save the lecture
            }

            hu.close(); //close the connection

            response.sendRedirect("CourseLessonEdit");
        } else { //EDIT LESSON
            id = Long.parseLong(request.getParameter("Lessonid"));

            LessonDao ld = new LessonDao(hu.openSession());
            Lesson lec = ld.get(id); //get the lesson object

            lec.setName(name); //update the attribtues
            lec.setDescription(description);
            lec.setFreeLesson(freeLesson);

            if (name == null || name.trim().equals("") || request.getParameter("course").equals("0")) {
                sendForward(request, response, lec.getId(), true);
                return;
            }

            if (request.getParameter("islive") != null) { //if is live is checked
                LiveLessonDao lld = new LiveLessonDao(hu.openSession());
                //Get attributes

                if (request.getParameter("hour").equals("-") || request.getParameter("minute").equals("-") || request.getParameter("day").equals("-") || request.getParameter("month").equals("-") || request.getParameter("year").equals("-") || request.getParameter("embedStream").trim().equals("") || request.getParameter("embedStream") == null) {
                    sendForward(request, response, courseid, true);
                    return;
                }

                //Get the date from the form
                int hour = Integer.parseInt(request.getParameter("hour"));
                int minute = Integer.parseInt(request.getParameter("minute"));
                int day = Integer.parseInt(request.getParameter("day"));
                int month = Integer.parseInt(request.getParameter("month"));
                int year = Integer.parseInt(request.getParameter("year"));
                String embedStream = request.getParameter("embedStream");

                if (lec.isLiveLesson()) { //if the old lecture is already a live, it means update
                    LiveLesson livelesson = lld.getLiveLessonFromLessonId(lec.getId());
                    livelesson.setDate(year, month, day, hour, minute);
                    livelesson.setEmbedStream(embedStream);
                    lld.update(livelesson);
                } else { //otherwise, it means a new live lecture insert
                    LiveLesson livelesson = new LiveLesson(System.nanoTime(), lec, "not started", embedStream);
                    livelesson.setDate(year, month, day, hour, minute);
                    lld.save(livelesson);
                    lec.setLiveLesson(true); //set live lesson as true
                }
            } else { //if the live lesson checkbox is not checked, make sure to delete it if it already exists
                if (lec.isLiveLesson()) { //if the old one is set as live, delete the old livelesson
                    LiveLessonDao lld = new LiveLessonDao(hu.openSession());
                    LiveLesson livelesson = lld.getLiveLessonFromLessonId(lec.getId());
                    lld.delete(livelesson);

                    lec.setLiveLesson(false); //set as live lesson as false
                }
            }

            Course courseselected = cdao.get(Long.parseLong(request.getParameter("course")));

            lec.setCourse(courseselected);
            ld.update(lec);
            hu.close(); //close connection
            response.sendRedirect("CourseLessonEdit"); //redirect
        }
    }

    /*
     * this method removes a lesson
     */
    public void removeLesson(long id, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        LessonDao ld = new LessonDao(hu.openSession());
        Long courseid = ld.get(id).getCourse().getId(); //get the course id

        ld.delete(ld.get(id)); //delete the course
        hu.close(); //close connection

        response.sendRedirect("CourseLessonEdit"); //redirect
    }

    /*
     * this method controls the modification of a lesson (jsp page)
     */
    public void editLesson(long id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get all the information about the teacher to fill in the form.
        HibernateUtil hu = new HibernateUtil();
        LessonDao ed = new LessonDao(hu.openSession());
        long courseid = ed.get(id).getCourse().getId();

        Lesson temp = ed.get(id); //get the lesosn object

        if (temp != null) {
            request.setAttribute("Lessonedit", temp);
            if (temp.isLiveLesson()) { //get live lesson object if it is already a live lesson
                LiveLessonDao lld = new LiveLessonDao(hu.openSession());
                LiveLesson livelesson = lld.getLiveLessonFromLessonId(temp.getId());
                request.setAttribute("editDate", true);
                //get the date
                request.setAttribute("day", livelesson.getDate().getTime().getDay());
                request.setAttribute("month", livelesson.getDate().getTime().getMonth());
                request.setAttribute("year", livelesson.getDate().getTime().getYear());
                request.setAttribute("minute", livelesson.getDate().getTime().getMinutes());
                request.setAttribute("hour", livelesson.getDate().getTime().getHours());
                
                request.setAttribute("livelesson", livelesson); //prepare live lesson object for modifivation
            }
        } 

        CourseDao de = new CourseDao(hu.openSession());

        List<Course> cl = de.findAll();
        request.setAttribute("allcourses", cl); //set all courses list
        request.setAttribute("courseid", courseid); //set the current course id in the attribute

        // Breadcrumbs
        Breadcrumbs[] breadcrumbs = {
            new Breadcrumbs("Index", "Home"),
            new Breadcrumbs("CourseLessonEdit", "Manage lessons"),
            new Breadcrumbs("Lesson?id", "Edit lesson")
        };
        request.setAttribute("breadcrumbs", breadcrumbs);

        hu.close(); //close connection
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_lessons.jsp");
        dispatcher.forward(request, response);
    }

    /*
     * this method redirects a user to the lesson page or manage lesson page, depending on the parameter.
     */
    public void sendForward(HttpServletRequest request, HttpServletResponse response, long id, boolean edit) throws IOException {
        if (edit) {
            response.sendRedirect("Lesson?id=" + id);
        } else {
            response.sendRedirect("ManageLesson?courseid=" + id);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
